class User < TwitterAuth::GenericUser
  # Extend and define your user model as you see fit.
  # All of the authentication logic is handled by the 
  # parent TwitterAuth::GenericUser class.
  
  # issues 
  # 1. delete that index-orig.html
  # 2. redirect from twitter to cloud page
  # 3. have ajax poll to gradually pull in data for each friend one by one or move to batch and go to dms
  
  # socially translucent - explicit vs implicit activity being shown...?
  
  def self.friend_profiles(twitter_id)
    profiles = Friend.find(:all,
                :select => 'f.*, u.screen_name, u.name, u.statuses_count AS `count`, u.profile_image_url AS `image`, COUNT(s.twitter_id)/SUM(TO_DAYS(NOW()) - TO_DAYS(s.twitter_created_at)) AS score',
                :joins => 'f JOIN twitter_users u ON u.twitter_id = f.friend_id JOIN statuses s ON s.user_id = f.friend_id',
                :conditions => "f.user_id = #{twitter_id}",
                :group => 'f.friend_id')
  end
  
  def self.friend_profile(twitter_id, friend_id)
    profile = Friend.find(:first,
                :select => 'f.*, u.screen_name, u.name, u.statuses_count AS `count`, u.profile_image_url AS `image`, COUNT(s.twitter_id)/SUM(TO_DAYS(NOW()) - TO_DAYS(s.twitter_created_at)) AS score',
                :joins => 'f JOIN twitter_users u ON u.twitter_id = f.friend_id JOIN statuses s ON s.user_id = f.friend_id',
                :conditions => "f.user_id = #{twitter_id} AND f.friend_id = #{friend_id}",
                :group => 'f.friend_id')
  end
  
  def self.friend_profile_including_those_with_no_statuses(twitter_id, friend_id)
    profile = Friend.find(:first,
                :select => 'f.*, u.screen_name, u.name, u.statuses_count AS `count`, u.profile_image_url AS `image`, COUNT(s.twitter_id)/SUM(TO_DAYS(NOW()) - TO_DAYS(s.twitter_created_at)) AS score',
                :joins => 'f JOIN twitter_users u ON u.twitter_id = f.friend_id LEFT JOIN statuses s ON s.user_id = f.friend_id',
                :conditions => "f.user_id = #{twitter_id} AND f.friend_id = #{friend_id}",
                :group => 'f.friend_id')
  end
  
  def refresh
    friends = self.friends
    friends.each {|f| self.friend_statuses(f.friend_id)}
  end

  def friends
    friends = Friend.find_all_by_user_id(self.twitter_id)
    hash = Hash.new
    friends.each{|f| hash[f.friend_id]=f} unless friends.nil?
    if friends.nil? or self.friends_requires_refresh?
      twitter_friends = self.twitter.get('/statuses/friends')
      twitter_friends.each do |f|
        begin
          hash.delete(f['id']) unless friends.nil?
          friend = Friend.find_by_user_id_and_friend_id(self.twitter_id, f['id'])
          friend.user_id_will_change!
          friend.save! # not sure how to force update here 
        rescue 
          Friend.create(:user_id => self.twitter_id, :friend_id => f['id'])
        end
        friend = TwitterUser.find_by_twitter_id f['id']
        if friend.nil?
          f['twitter_id']=f['id']
          f.delete('status')
          friend = TwitterUser.create!(f)
        end
      end
      # anything remaining in hash should be deleted
      hash.each do |h|
        # would like this to be paranoid ...
        Friend.find_by_user_id_and_friend_id(self.twitter_id, h[friend_id]).destroy
      end
      friends = Friend.find_all_by_user_id(self.twitter_id)
    end
    friends
  end
  # my twitter_id 11266912
  def friends_requires_refresh?
    friend = Friend.find(:first, :conditions => ["user_id = ?",self.twitter_id], :order=>'updated_at DESC')
    friend.updated_at < (Time.now - 1.hour) rescue true
  end
  # catch  TwitterAuth::Dispatcher::Error
  def friend_statuses(user_id)
    statuses = Status.find_all_by_user_id(user_id)
    begin
      if statuses.nil? or self.statuses_requires_refresh?(user_id)
        twitter_statuses = self.twitter.get("/statuses/user_timeline.json?id=#{user_id}")
        twitter_statuses.each do |s|
          begin
            status = Status.find_by_twitter_id(s['id'])
            status.user_id_will_change!
            status.save!
          rescue 
            s['twitter_id']=s['id']
            s['user_id'] = user_id
            s['twitter_created_at'] = s['created_at']
            s.delete('created_at')
            s.delete('user')
            Status.create(s)
          end
        end
        #statuses = Status.find_all_by_user_id(user_id)
      end
    rescue Exception => exc
      # can't grab any more data at present ...
      logger.error("#{exc.class.inspect}: #{exc.message}")
    end
   # statuses  
  end
  
  def statuses_requires_refresh?(user_id)
    status = Status.find(:first, :conditions => ["user_id = ?",user_id], :order=>'updated_at DESC')
    status.updated_at < (Time.now - 1.hour) rescue true
  end
end
